/**
 * 中国象棋游戏引擎
 * 统一管理游戏状态、规则验证、移动执行等
 */

import { GameState } from './GameState.js';
import { 
  isValidMove, 
  makeMove, 
  getAllValidMoves,
  getValidMovesForPiece,
  checkGameEnd,
  isInCheck 
} from '../rules/gameRules.js';
import { COLORS, PIECE_TYPES } from '../constants/pieces.js';
import { GAME_STATUS } from '../constants/gameConfig.js';

export class ChessEngine {
  constructor() {
    this.gameState = new GameState();
    this.moveListeners = [];
    this.gameEndListeners = [];
  }

  /**
   * 重置游戏
   */
  reset() {
    this.gameState.reset();
    this.notifyGameEnd({ type: 'reset', message: '游戏已重置' });
    return {
      success: true,
      message: '游戏已重置'
    };
  }

  /**
   * 获取当前棋盘状态
   */
  getBoard() {
    return this.gameState.board;
  }

  /**
   * 获取当前玩家
   */
  getCurrentPlayer() {
    return this.gameState.currentPlayer;
  }

  /**
   * 获取游戏状态
   */
  getGameStatus() {
    return this.gameState.status;
  }

  /**
   * 获取指定位置的棋子
   */
  getPieceAt(row, col) {
    return this.gameState.getPieceAt(row, col);
  }

  /**
   * 获取移动历史
   */
  getMoveHistory() {
    return this.gameState.moveHistory;
  }

  /**
   * 获取被吃棋子
   */
  getCapturedPieces() {
    return this.gameState.capturedPieces;
  }

  /**
   * 获取最后一步移动
   */
  getLastMove() {
    return this.gameState.lastMove;
  }

  /**
   * 获取游戏信息
   */
  getGameInfo() {
    const gameEndInfo = checkGameEnd(
      this.gameState.board, 
      this.gameState.currentPlayer, 
      this.gameState.moveHistory
    );

    return {
      currentPlayer: this.gameState.currentPlayer,
      status: this.gameState.status,
      moveCount: this.gameState.moveCount,
      capturedCount: {
        [COLORS.RED]: this.gameState.capturedPieces[COLORS.RED].length,
        [COLORS.BLACK]: this.gameState.capturedPieces[COLORS.BLACK].length
      },
      isInCheck: {
        [COLORS.RED]: isInCheck(this.gameState.board, COLORS.RED),
        [COLORS.BLACK]: isInCheck(this.gameState.board, COLORS.BLACK)
      },
      canUndo: this.gameState.moveHistory.length > 0,
      gameEndInfo
    };
  }

  /**
   * 执行移动
   */
  makeMove(from, to) {
    // 检查游戏是否已结束
    if (this.gameState.status !== GAME_STATUS.PLAYING) {
      return {
        success: false,
        message: '游戏已结束'
      };
    }

    // 执行移动验证和执行
    const moveResult = makeMove(
      this.gameState.board, 
      from, 
      to, 
      this.gameState.currentPlayer
    );

    if (moveResult.success) {
      // 更新游戏状态
      this.gameState.board = moveResult.board;
      this.gameState.moveCount++;
      this.gameState.currentPlayer = this.gameState.currentPlayer === COLORS.RED 
        ? COLORS.BLACK 
        : COLORS.RED;

      // 更新移动历史
      if (moveResult.moveInfo) {
        this.gameState.moveHistory.push({
          ...moveResult.moveInfo,
          moveNumber: this.gameState.moveCount,
          timestamp: Date.now()
        });
        this.gameState.lastMove = moveResult.moveInfo;
      }

      // 更新被吃棋子
      if (moveResult.moveInfo && moveResult.moveInfo.capturedPiece) {
        this.gameState.capturedPieces[moveResult.moveInfo.capturedPiece.color].push(
          moveResult.moveInfo.capturedPiece
        );
      }

      // 检查游戏是否结束
      const gameEndInfo = checkGameEnd(
        this.gameState.board,
        this.gameState.currentPlayer,
        this.gameState.moveHistory
      );

      if (gameEndInfo.isEnd) {
        this.gameState.status = gameEndInfo.status;
        // console.log('🎯 游戏结束检测:', gameEndInfo);
        
        // 通知游戏结束
        this.notifyGameEnd(gameEndInfo);
      }

      // 更新游戏状态
      if (moveResult.gameStatus) {
        this.gameState.status = moveResult.gameStatus;
      }

      // 通知移动完成
      this.notifyMove(moveResult);
    }

    return moveResult;
  }

  /**
   * 撤销移动
   */
  undoMove() {
    if (this.gameState.moveHistory.length === 0) {
      return {
        success: false,
        message: '没有可撤销的移动'
      };
    }

    const success = this.gameState.undoLastMove();
    
    if (success) {
      // 重置游戏状态为进行中（如果之前已结束）
      this.gameState.status = GAME_STATUS.PLAYING;
      
      return {
        success: true,
        message: '撤销成功'
      };
    } else {
      return {
        success: false,
        message: '撤销失败'
      };
    }
  }

  /**
   * 获取指定位置棋子的有效移动
   */
  getValidMoves(position) {
    if (this.gameState.status !== GAME_STATUS.PLAYING) {
      return [];
    }

    return getValidMovesForPiece(
      this.gameState.board, 
      position, 
      this.gameState.currentPlayer
    );
  }

  /**
   * 获取所有有效移动
   */
  getAllValidMoves(color = null) {
    const targetColor = color || this.gameState.currentPlayer;
    return getAllValidMoves(this.gameState.board, targetColor);
  }

  /**
   * 检查指定颜色是否被将军
   */
  isInCheck(color = null) {
    const targetColor = color || this.gameState.currentPlayer;
    return isInCheck(this.gameState.board, targetColor);
  }

  /**
   * 添加移动监听器
   */
  addMoveListener(listener) {
    this.moveListeners.push(listener);
  }

  /**
   * 移除移动监听器
   */
  removeMoveListener(listener) {
    const index = this.moveListeners.indexOf(listener);
    if (index > -1) {
      this.moveListeners.splice(index, 1);
    }
  }

  /**
   * 添加游戏结束监听器
   */
  addGameEndListener(listener) {
    this.gameEndListeners.push(listener);
  }

  /**
   * 移除游戏结束监听器
   */
  removeGameEndListener(listener) {
    const index = this.gameEndListeners.indexOf(listener);
    if (index > -1) {
      this.gameEndListeners.splice(index, 1);
    }
  }

  /**
   * 通知移动完成
   */
  notifyMove(moveResult) {
    this.moveListeners.forEach(listener => {
      try {
        listener(moveResult);
      } catch (error) {
        console.error('Move listener error:', error);
      }
    });
  }

  /**
   * 通知游戏结束
   */
  notifyGameEnd(gameEndInfo) {
    this.gameEndListeners.forEach(listener => {
      try {
        listener(gameEndInfo);
      } catch (error) {
        console.error('Game end listener error:', error);
      }
    });
  }

  /**
   * 确定获胜者
   */
  determineWinner(gameStatus) {
    switch (gameStatus) {
      case GAME_STATUS.CHECKMATE:
        // 当前玩家被将死，对手获胜
        return this.gameState.currentPlayer === COLORS.RED ? COLORS.BLACK : COLORS.RED;
      case GAME_STATUS.STALEMATE:
      case GAME_STATUS.DRAW:
        return null; // 和棋
      default:
        return null;
    }
  }

  /**
   * 克隆引擎状态（用于AI计算）
   */
  clone() {
    const cloned = new ChessEngine();
    cloned.gameState = this.gameState.clone();
    return cloned;
  }

  /**
   * 导出游戏状态（用于保存/加载）
   */
  exportState() {
    return {
      board: this.gameState.board,
      currentPlayer: this.gameState.currentPlayer,
      status: this.gameState.status,
      moveHistory: this.gameState.moveHistory,
      capturedPieces: this.gameState.capturedPieces,
      moveCount: this.gameState.moveCount,
      timestamp: Date.now()
    };
  }

  /**
   * 导入游戏状态
   */
  importState(state) {
    try {
      this.gameState.board = state.board;
      this.gameState.currentPlayer = state.currentPlayer;
      this.gameState.status = state.status;
      this.gameState.moveHistory = state.moveHistory || [];
      this.gameState.capturedPieces = state.capturedPieces || { [COLORS.RED]: [], [COLORS.BLACK]: [] };
      this.gameState.moveCount = state.moveCount || 0;
      this.gameState.lastMove = this.gameState.moveHistory.length > 0 
        ? this.gameState.moveHistory[this.gameState.moveHistory.length - 1] 
        : null;
      
      return {
        success: true,
        message: '状态导入成功'
      };
    } catch (error) {
      return {
        success: false,
        message: '状态导入失败: ' + error.message
      };
    }
  }
}